package com.chatsocket.util;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.chatsocket.model.EchoBody;
import com.chatsocket.socketServlet.WebSocketUtils;

/**
 *聊天每个用户对应单位 chat 
 */
public class Chat {
	/*当前用户*/
	private String current;
	/**目标用户  userType_userId*/
	private String destination;
	/**目标用户  userType_userId*/
//	private String threadId;
	public void sendMessage(String text,Integer textType,String httpServletSessionId){
		Message message=new Message();
		message.setTime(new Date());
		message.setContent(text);
		message.setContentType(textType);
		message.setOrigin(current);
		message.setDestination(destination);
//		List<String> httpServletSessionIds= Constant.USER_ONLINE_SESSION.get(destination);
		//先存库 后发送
		List<String> httpServletSessionIds=WebSocketUtils.getSessionIdsByDestination(destination);
		message.setDestinationSessionIds(httpServletSessionIds);
		List<Message> list = Constant.USER_DESTINATION_MSG.get(destination);
		if(list==null){
			list=new CopyOnWriteArrayList<Message>();
		}
		list.add(message);
		Constant.USER_DESTINATION_MSG.put(destination, list);
		//FIXME 1 发送消息标记
		WebSocketUtils.notifyUser(destination,EchoBody.hasNewMsg());
		
		//2 发送给同一用户其他session
		List<String> httpServletSessionIdSelfs=WebSocketUtils.getSessionIdsByDestination(current);
		if(httpServletSessionIdSelfs!=null){
			httpServletSessionIdSelfs.remove(httpServletSessionId);
		}
		message.setOriginSessionIds(httpServletSessionIdSelfs);
		List<Message> list2 = Constant.USER_ORIGIN_MSG.get(current);
		if(list2==null){
			list2=new CopyOnWriteArrayList<Message>();
		}
		list2.add(message);
		Constant.USER_ORIGIN_MSG.put(current, list2);
		//FIXME 2 发送发送消息标记
		WebSocketUtils.notifyUser(current,EchoBody.newMsgSelf());
	}
//	public String getThreadId() {
//		return threadId;
//	}
//	public void setThreadId(String threadId) {
//		this.threadId = threadId;
//	}
	public String getCurrent() {
		return current;
	}
	public void setCurrent(String current) {
		this.current = current;
	}
	public String getDestination() {
		return destination;
	}
	public void setDestination(String destination) {
		this.destination = destination;
	}
}
